var bookAPI = (function($) {
	var ymPicker;
	var limit = 20,start=0,pulling = false
	var upPullElement
	var sourceData = []
	var pageType='',loginPerID = '',PersonNo
	var method=''
	$.init();
	
	$.plusReady(function() {
		var _self = plus.webview.currentWebview();
		_self.setStyle({
			popGesture: 'none'  // 作用于ios 禁止右滑关闭
		});
		plus.navigator.setStatusBarBackground('#24af96');
		plus.navigator.setStatusBarStyle('light');
		mui.back = function() {
			plus.navigator.setStatusBarBackground('#fff')
			plus.navigator.setStatusBarStyle('dark');
			_self.close("auto");
		}
		baseSetup();
	});

	function getBookList(){
		if (pulling) {
			upPullElement.endPullUpToRefresh(false);
			return;
		}
		pulling = true;
		var yearMonth = document.getElementById('yearMonth');
		var daysCount = getMonthMaxDay(yearMonth.innerHTML);
		var stDate = yearMonth.innerHTML +'-01';
		var endDate = yearMonth.innerHTML +'-'+daysCount;
		var pdict = {'perId':loginPerID,'parr':'StDate|'+stDate+'^EndDate|'+endDate,start: start,limit: limit}
		if (pageType == 'patent') {
			pdict.parr = 'PatStDate|'+stDate+'^PatEndDate|'+endDate+'^PatName|^PatNum|'
		}
		var paramDict = {'method':method,'params':JSON.stringify(pdict),'type':'RecQuery'}
		// console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			plus.nativeUI.closeWaiting();
			if (result.msgcode != '1') {
				mui.toast(result.msg)
				if (upPullElement != null) {
					upPullElement.endPullUpToRefresh(false);
				}
				return;
			}
			var dataArr = result.data;
			// console.log(JSON.stringify(dataArr))
			sourceData = sourceData.concat(dataArr)
			updateBATPAUI(dataArr);
			if (upPullElement) {
				upPullElement.endPullUpToRefresh(dataArr.length < limit);
			}
			start += dataArr.length;
			pulling = false;
		}, function(errorStr) {
			pulling = false;
			if (upPullElement != null) {
				upPullElement.endPullUpToRefresh(false);
			}
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
		});
	}
	
	function updateBATPAUI(dataArr){
		var tableUl = document.getElementById('tableUl');
		var lis = tableUl.querySelectorAll('li');
		var oldLength = lis.length;
		for(var i = 0; i < dataArr.length; i++) {
			var oneDict = dataArr[i];
			if (oneDict == null || oneDict == '') {
				continue;
			}
			var oneLi = document.createElement('li');
			oneLi.setAttribute('class', 'mui-table-view-cell');
			oneLi.id = (oldLength + i)+'-';
			tableUl.appendChild(oneLi);
			
			var AddDate = oneDict['AddDate'];
			if (AddDate != null && AddDate.length >= 10) {
				AddDate = AddDate.substr(5, 5)
			}
			var AddTime = oneDict['AddTime'];
			if (AddTime != null && AddTime.length >= 5) {
				AddTime = AddTime.substr(0, 5)
			}
			//保存Y 提交S 护士长审核通过H  护理部审核通过R 作废N
			var classStr = 'undealed';
			var flagStr = oneDict['RecFlag']
			if (pageType == 'patent') {
				flagStr = oneDict['PatValid']
			}else if (pageType == 'artical') {
				flagStr = oneDict['ArtValid']
			}
			if(flagStr == 'Y') {
				classStr = '';
			} else if(flagStr == 'A') { 
				classStr = 'nurPassed';
			}else if (flagStr == 'R') {
				classStr = 'passed';
			}else if (flagStr == 'N') {
				classStr = 'unValid';
			} else if(flagStr == 'B') {
				classStr = 'refused'
			}
			var addDate = AddDate + '&nbsp;' + AddTime;
			var firstNurId = '';
			if (pageType == 'award') { //科研获奖
				firstNurId = oneDict['ScienFirNo']+ ''
				oneLi.innerHTML = '<div class="bookName">'+oneDict['ScienName']+'</div>'+
//				'<div class="publish">获奖项目名称: '+oneDict['awardproname']+'</div>'+//无数据是否不重要
				'<div class="publish">奖项信息: '+oneDict['ScienSourceDesc']+'/'+
					oneDict['ScienGradeDesc']+'/'+oneDict['ScienTypeDesc']+'</div>'+
				'<div class="publish">完成人: 1.'+oneDict['ScienFirPerDesc']+'、2.'+
					oneDict['ScienSecPerDesc']+'、3.'+oneDict['ScienThirdPerDesc']+'</div>'+
//				'<div class="publish">其它完成人: '+oneDict['awardothper']+'</div>'+
				'<div class="publish">获奖日期: '+oneDict['ScienDate']+'</div>'+
//				'<div class="addDate">'+'addDate'+'</div>'+
				'<div class="applyStatus '+classStr+'">'+oneDict['RecFlagDesc']+'</div>';
			}else if (pageType == 'topic') { //课题立项
				firstNurId = oneDict['FirstResponser']+ ''
				oneLi.innerHTML = '<div class="bookName">'+oneDict['ProjectName']+'</div>'+
				'<div class="publish">课题信息: '+oneDict['ProjectGradeDesc']+'/'+
					oneDict['ProjectTypeDesc']+'</div>'+
				'<div class="publish">负责人: 1.'+oneDict['FirstResponserDesc']+'、2.'+
					oneDict['SecondResponserDesc']+'、3.'+oneDict['ThirdResponserDesc']+'</div>'+
//				'<div class="publish">其它参与者: '+oneDict['otherrespon']+'</div>'+
				'<div class="publish">立项日期: '+oneDict['ProjectDate']+'</div>'+
				'<div class="publish">预计完成日期: '+oneDict['FinishDate']+'</div>'+
//				'<div class="addDate">'+'addDate'+'</div>'+
				'<div class="applyStatus '+classStr+'">'+oneDict['RecFlagDesc']+'</div>';
			}else if (pageType == 'patent') { //护理专利
				firstNurId = oneDict['PatFirInventor']+ ''
				var firStr = oneDict['PatFirInventorDesc'];
				if (firStr == '' && oneDict['PatFirInventor'] != '') {
					firStr = oneDict['PatFirInventor']
				}
				var secStr = '';
				var thirStr = '';
				if(oneDict['PatSecInventorDesc']){
					secStr = '、' + oneDict['PatSecInventorDesc'];
					
				}
				if(oneDict['PatThiInventorDesc']){
					thirStr = '、' + oneDict['PatThiInventorDesc'];
				}
				oneLi.innerHTML = '<div class="bookName">'+oneDict['PatName']+'</div>'+
//				'<div class="publish">专利权人: '+oneDict['PatPerson']+'</div>'+
				'<div class="publish">专利类型：'+oneDict['PatTypeDesc']+'</div>'+
				'<div class="publish">发明人：'+ firStr + secStr + thirStr + '</div>'+
//				'<div class="publish">其它发明人: '+oneDict['PatOthInventor']+'</div>'+
				'<div class="publish">授权单位：'+oneDict['PatAutUnitDesc']+'</div>'+
				'<div class="publish">专利授权公告日：'+oneDict['PatAutAnnDate']+'</div>'+
//				'<div class="addDate">'+'addDate'+'</div>'+
				'<div class="applyStatus '+classStr+'">'+oneDict['PatValidDesc']+'</div>';
			}else if (pageType == 'artical') { //文章管理
				firstNurId = oneDict['ArtFirAuthorNo']+ ''
				oneLi.innerHTML = '<div class="bookName">'+oneDict['ArtTitle']+'</div>'+
				'<div class="publish">杂志名称: '+oneDict['ArtMagazineDesc']+'</div>'+
				'<div class="publish">文章信息: '+oneDict['ArtCategoryDesc']+'/'+oneDict['ArtTypeDesc']+'/'+
					oneDict['ArtHeadingDesc']+'</div>'+
				'<div class="publish">'+dealUndefined(oneDict['ArtAuthorTypeDesc'])+': '+oneDict['ArtFirAuthorDesc']+'</div>'+
				'<div class="publish">发表日期: '+oneDict['ArtDate']+'</div>'+
//				'<div class="addDate">'+'addDate'+'</div>'+
				'<div class="applyStatus '+classStr+'">'+oneDict['ArtValidDesc']+'</div>';
			}else if (pageType == 'work') { // 著作
				firstNurId = oneDict['Creator']+ ''
				//// 是否与院外合作 CoOutFlag 出版日期PublishDate 书籍ISBN号BookNo
				// 中国图书馆CIP核字 CipNo 作者类型 AuthorType 著作作者 AuthorDR
				oneLi.innerHTML = '<div class="bookName">'+oneDict['BookName']+'</div>'+
				'<div class="publish">著作类型: '+oneDict['WorkTypeDesc']+'</div>'+
				'<div class="publish">出版类型: '+oneDict['PressTypeDesc']+'</div>'+
				'<div class="publish">出版日期: '+oneDict['PublishDate']+'</div>'+
				'<div class="publish">出版社名称: '+oneDict['PressName']+'</div>'+
				'<div class="publish">'+oneDict['AuthorTypeDesc']+': '+oneDict['AuthorDesc']+'</div>'+
				'<div class="applyStatus '+classStr+'">'+oneDict['RecFlagDesc']+'</div>';
			}else if (pageType == 'trans') { // 成果转化
				firstNurId = oneDict['Creator']+ ''
				//转化方式  TransType
				// 提成方式 TakeType 受让单位 TransOrg 受让单位联系人TransPer
				//受让单位联系方式 TransPhone 合同编号ContractNo 合同签订日期SignDate 合同生效日期ValidDate
				//转让金额(万元) TransAmount 到账日期ReceiptDate 已到账金额(万元)ReceivedAmount
				//第一完成人 FirstPerDesc SecPerDesc ThirdPerDesc OtherPer
					oneLi.innerHTML = '<div class="bookName">'+oneDict['WorkName']+'</div>'+
					'<div class="publish">专利类型: '+oneDict['PatentTypeDesc']+'</div>'+
					'<div class="publish">转化方式: '+oneDict['TransTypeDesc']+'</div>'+
					'<div class="publish">提成方式: '+oneDict['TakeTypeDesc']+'</div>'+
					'<div class="publish">受让信息: '+oneDict['TransOrg']+'&nbsp;&nbsp;'+
						oneDict['TransPer']+'&nbsp;&nbsp;'+ oneDict['TransPhone']+'</div>'+
					'<div class="publish">完成人: 1.'+oneDict['FirstPerDesc']+'、2.'+oneDict['SecPerDesc']+'、3.'+
						oneDict['ThirdPerDesc']+'</div>'+
					'<div class="publish">其它完成人：'+oneDict['OtherPer']+'</div>'+
					'<div class="applyStatus '+classStr+'">'+oneDict['RecFlagDesc']+'</div>';
			}
			// console.log(PersonNo,firstNurId);
			// 未审核Y 护士长审核通过A  护理部审核通过R   作废N  驳回B
			// 不是A和R都可以改
			if (PersonNo != firstNurId || flagStr == 'A' ||flagStr == 'R') {
				oneLi.setAttribute('data-flag','detail')
			}
		}
	}
	function tableViewCellTapped(){
		if (this.getAttribute('data-flag') == 'detail') {
			showBookDetail(this)
		}else{
			addBtnTapped(this)
		}
	}
	function showBookDetail(li){
		var index = parseInt(li.id);
		var pageData = sourceData[index]
		mui.openWindow({
			url:'book-detail.html',
			id:'book-detail',
			extras:{
				pageData:pageData,
				type:pageType,
				fromPage:'person-info'
			}
		});
	}
	
	function addBtnTapped(btn){
		var type = 'create';
		var pageData = undefined;
		if (btn.id != 'addBtn') {
			type = 'edit';
			var index = parseInt(btn.id);
			pageData = sourceData[index];
		}
		// console.log(JSON.stringify(pageData))
		var createPage = mui.openWindow({
			url:pageType+'-create.html',
			id:'createBook',
			extras:{
				pageData:pageData
			}
		});
	}
	
	function baseSetup() {
		mui('#slider').slider().stopped = true; //禁止左右滑动
		mui('#tableUl').on('tap','li',tableViewCellTapped) 
		var title = plus.webview.currentWebview().title
		// console.log(plus.webview.currentWebview().id);
		mui('.mui-title')[0].innerHTML = title
		var perInfo = app.getState()
		if (perInfo) {
			loginPerID = perInfo.loginPerID
			PersonNo = perInfo.usercode
			//console.log(JSON.stringify(perInfo));
		}
		switch (title){
			case '课题立项':
				pageType = 'topic'
				PersonNo = perInfo.loginPerID
				method = 'web.INMPerSubComm:ListResearchProject'
				break;
			case '科研获奖':
				pageType = 'award'
				method = 'web.INMPerSubComm:ListResearchAward'
				break;
			case '护理专利':
				PersonNo = perInfo.loginPerID
				pageType = 'patent'
				method = 'web.INMPerSubComm:ListPatent'
				break;
			case '文章管理':
				pageType = 'artical'
				method = 'web.INMPerSubComm:ListArticle'
				break;
			case '著作':
				PersonNo = perInfo.loginID
				pageType = 'work'
				method = 'web.INMSMComm:FindSciWorkList'
				break;
			case '成果转化':
				PersonNo = perInfo.loginID
				pageType = 'trans'
				method = 'web.INMSMComm:FindSciTransList'
				break;
			default:
				break;
		}
		var yearMonth = document.getElementById('yearMonth');
		if (plus.os.name == 'iOS') {
			ymPicker = new mui.xhPicker(2,'请选择月份','pickerId2');
			var dateArr = []
			var monArr = []
			for (var i = 0; i < 12; i++) {
				var text = (i+1)
				if (text < 10) {
					text = '0'+text
				}
				monArr[i] = {'text':text}
			}
			var yearInt = new Date().getFullYear()-5;
			for (var i = 0; i < 11; i++) {
				dateArr[i] = {'text':yearInt+i,'children':monArr}
			}
			ymPicker.setData(dateArr);
			yearMonth.addEventListener('tap', iOSSelectYearMonth, false);
		}else{
			yearMonth.addEventListener('tap', selectYearMonth, false);
		}
		mui('.mui-scroll-wrapper').scroll();
		mui('body').on('tap','#addBtn',function(){
			addBtnTapped(this)
		}) 
		
		var scrolls = document.querySelectorAll('.mui-slider-group .mui-scroll');
		mui.each(scrolls,function(index, pullRefreshEl){
			mui(pullRefreshEl).pullToRefresh({
				up: {
					auto: false,
					callback: function() {
						upPullElement = this;
						getBookList();
					}
				}
			});
		});
		var today = getTodayStr();
		thisMonthStr = today.substring(0,today.length - 3);
		yearMonth.innerText = thisMonthStr;
		var thisMonth = document.getElementById('thisMonth');
		thisMonth.addEventListener('tap', function() {
			var yearMonth = document.getElementById('yearMonth');
			yearMonth.innerText = thisMonthStr;
			resetPullRefresh();
		}, false);
		var lastMonth = document.getElementById('lastMonth');
		lastMonth.addEventListener('tap',function(){
			var yearMonth = document.getElementById('yearMonth');
			yearMonth.innerText = getFullLastMonth(yearMonth.innerText);
			resetPullRefresh();
		});
		var nextMonth = document.getElementById('nextMonth');
		nextMonth.addEventListener('tap',function(){
			var yearMonth = document.getElementById('yearMonth');
			yearMonth.innerText = getFullNextMonth(yearMonth.innerText);
			resetPullRefresh();
		});
		
		resetPullRefresh();
	}
	
	function selectYearMonth(){
		var _self = this;
		if(_self.picker) {
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				_self.picker.dispose();
				_self.picker = null;
				resetPullRefresh();
			});
		} else {
			var optionsJson = '{"type":"month"}';
			var options = JSON.parse(optionsJson);
			_self.picker = new mui.DtPicker(options);
			_self.picker.show(function(rs) {
				_self.innerText = rs.text;
				_self.picker.dispose();
				_self.picker = null;
				resetPullRefresh();
			});
		}
	}
	function iOSSelectYearMonth(){
		var btnDom = this
		ymPicker.show(function(items) {
			btnDom.innerText = items[0]['text']+'-'+items[1]['text'];
			resetPullRefresh();
		});
	}
	
	var resetPullRefresh =function(){
		mui('#tableUl').off('tap','li',tableViewCellTapped) 
		var tableView = document.getElementById('tableUl');
		tableView.innerHTML = '';
		mui('#tableUl').on('tap','li',tableViewCellTapped) 
		start = 0;
		sourceData.splice(0,sourceData.length);
		mui('#pullrefresh').scroll().scrollTo(0,0,100);
		if (upPullElement) { 
			upPullElement.refresh(true);
		}
		getBookList()
	}
	var api = {};
	api.refresh = resetPullRefresh;
	return api;
})(mui);

function resetRefresh(){
	bookAPI.refresh();
}

/* 人力资源
原始数据
	职务:'PersonheadshipDR':'护士长'  任职时间:PersonNurHeadDate:''  身高:PersonHeight:165
	白衣号:PersonClothesNO:L          鞋号:PersonShoeNO:38          婚姻:Personmarriage:已婚
	学历:PersonSchoolAgeDr:本科       学位:PersonDegreeDR:学士      政治面貌:PersonPolitydr:群众
	联系方式:PersonTelHand:13810703725  护士注册证书号:PersonRegNo:200911005026
	专业技术职称:PersonProfPostDR:''    取得职称时间:PersonTechPostDate:''
	现住址邮编:PersonPresentZipCode:100350   现住地址:PersonAddress:'北京市东城区'  
 
 Flag="V" s FlagDesc="待审批"
	e  i Flag="A" s FlagDesc="审核通过"
	e  i Flag="R" s FlagDesc="已驳回"*/

/* 
 * 科研获奖/课题立项/护理专利/文章上报列表查询依据
 * 1.科研获奖--获奖日期
 * 2.课题立项--立项日期
 * 3.护理专利--发明申请日
 * 4.文章上报--发表日期
 */